package view;

import service.impl.ScheduleServiceImpl;
import service.impl.TicketServiceImpl;
import util.InputUtil;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;

public class CounterView {
    private final ScheduleServiceImpl scheduleService = new ScheduleServiceImpl();
    private final TicketServiceImpl ticketService = new TicketServiceImpl();

    public void start() {
        while (true) {
            System.out.println("\n=== 前台菜单 ===");
            System.out.println("1. 售票");
            System.out.println("2. 退票");
            System.out.println("3. 查看排片");
            System.out.println("0. 退出登录");
            System.out.print("请选择：");
            switch (InputUtil.nextInt()) {
                case 1:
                    sellTicket();
                    break;
                case 2:
                    refundTicket();
                    break;
                case 3:
                    viewSchedules();
                    break;
                case 0:
                    scheduleService.shutdown();
                    ticketService.shutdown();
                    return;
                default:
                    System.out.println("输入错误！");
            }
        }
    }

    private void sellTicket() {
        System.out.print("输入场次ID：");
        String scheduleId = InputUtil.nextLine();
        entity.Schedule schedule = scheduleService.findById(scheduleId);
        if (schedule == null) {
            System.out.println("场次不存在！");
            return;
        }

        System.out.print("输入座位行号：");
        int row = InputUtil.nextInt();
        System.out.print("输入座位列号：");
        int col = InputUtil.nextInt();

        System.out.print("输入观众姓名：");
        String viewerName = InputUtil.nextLine();

        ticketService.add(new entity.Ticket(null, scheduleId, row, col, viewerName));
        System.out.println("售票成功！");
    }

    private void refundTicket() {
        System.out.print("输入电子票号：");
        String ticketId = InputUtil.nextLine();
        entity.Ticket ticket = ticketService.findById(ticketId);
        if (ticket == null) {
            System.out.println("票不存在！");
            return;
        }

        entity.Schedule schedule = scheduleService.findById(ticket.getScheduleId());
        if (schedule == null) {
            System.out.println("场次信息错误！");
            return;
        }

        long minutesUntilMovieStarts = ChronoUnit.MINUTES.between(LocalDateTime.now(), schedule.getStartTime());
        if (minutesUntilMovieStarts < 60) {
            System.out.println("退票失败，距离开场不足1小时！");
            return;
        }

        ticketService.delete(ticketId);
        System.out.println("退票成功！");
    }

    private void viewSchedules() {
        scheduleService.findAll().forEach(System.out::println);
    }
}